<template>

    <!-- 查询条件表单 新增按钮 启用禁用按钮 -->
    <el-form :module="searchForm" :inline="true" class="demo-form-inline">
        <el-form-item label="姓名：">
            <el-input v-model="searchForm.name" placeholder="姓名" />
        </el-form-item>
        <el-form-item label="工资：">
            <el-input v-model="searchForm.salary" placeholder="工资" />
        </el-form-item>
        <el-form-item>
            <el-button type="primary" plain :icon="Search" @click="find">查询</el-button>
            <el-button type="primary" plain :icon="DocumentAdd" @click="dialogAddFormVisible = true">新增</el-button>
            <el-button type="success" plain :icon="CircleCheck" @click="modifyStatus('1')">启用</el-button>
            <el-button type="danger" plain :icon="CircleClose" @click="modifyStatus('0')">禁用</el-button>
        </el-form-item>
    </el-form>

    <!-- 表格 -->
    <el-table :data="pageModel.tableData" stripe style="width: 100%" :row-class-name="tableRowClassName" highlight-current-row
        @current-change="handleCurrentRowChange">
        <el-table-column type="index" width="50px" />
        <el-table-column prop="name" label="姓名" />
        <el-table-column prop="sex" label="性别" :formatter="sexFormatter"></el-table-column>
        <el-table-column prop="salary" label="工资" />
        <el-table-column prop="hireDate" label="入职时间" :formatter="dateFormatter"></el-table-column>
        <el-table-column label="状态">
            <!-- 这里的 scope.row 就代表当前行的数据 -->
            <template #default="scope">
                <el-tag :type="getStatusTagType(scope.row.status)">{{ scope.row.status == '1' ? '启用' : '禁用' }}</el-tag>
            </template>
        </el-table-column>
        <el-table-column label="操作">
            <template #default="scope">
                <el-button type="primary" size="small" :icon="Edit" @click="showModify(scope.row)">编辑</el-button>
                <el-button type="danger" size="small" :icon="Delete" @click="remove(scope.row)">删除</el-button>
            </template>
        </el-table-column>
    </el-table>
    <div>
        <el-pagination v-model:current-page="searchForm.pageNo" v-model:page-size="searchForm.pageSize"
            :page-sizes="[2, 5, 10]" :background="true" layout="total, sizes, prev, pager, next, jumper"
            :total="pageModel.total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>






    <!-- 员工新增模态框 -->
    <el-dialog v-model="dialogAddFormVisible" title="员工新增" width="700px" @close="clear">
        <el-form :model="empForm" label-width="auto" style="max-width: 600px">
            <el-form-item label="姓名:">
                <el-input v-model="empForm.name" autocomplete="off" placeholder="请输入姓名"/>
            </el-form-item>
            <el-form-item prop="password" label="工资:">
                <el-input v-model="empForm.salary" type="password" show-password placeholder="请输入工资"/>
            </el-form-item>

            <el-form-item label="性别:">
                <el-radio-group v-model="empForm.sex">
                    <el-radio value="1">男</el-radio>
                    <el-radio value="0">女</el-radio>
                </el-radio-group>
            </el-form-item>

            <el-form-item label="学历:">
                <el-select v-model="empForm.edu" placeholder="请选择学历" clearable>
                    <template v-for="option in options" :key="option.value">
                        <el-option :label="option.label" :value="option.value" />
                    </template>
                </el-select>
            </el-form-item>

            <el-form-item label="爱好:">
                <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate" @change="handleCheckAllChange">
                    全选&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                </el-checkbox>
                <el-checkbox-group v-model="empForm.hobbies" @change="handleCheckedHobbiesChange">
                    <el-checkbox v-for="hobby in hobbies" :key="hobby.value" :value="hobby.value">
                        {{ hobby.label }}
                    </el-checkbox>
                </el-checkbox-group>
            </el-form-item>

            <el-form-item label="简介:">
                <el-input v-model="empForm.description" style="width: 800px" :rows="4" type="textarea"
                    placeholder="请输入简介" />
            </el-form-item>

            <el-form-item label="日期:">
                <el-date-picker v-model="empForm.hireDate" type="date" placeholder="请选择日期" format="YYYY年MM月DD日"
                    value-format="YYYY-MM-DD" />
            </el-form-item>
        </el-form>


        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogAddFormVisible = false">取消</el-button>
                <el-button type="primary" @click="add">
                    确认
                </el-button>
            </div>
        </template>
    </el-dialog>






    <!-- 员工修改模态框 -->
    <el-dialog v-model="dialogEditFormVisible" title="员工修改" width="700px" @close="clear">
        <el-form :model="empForm" label-width="auto" style="max-width: 600px">
            <el-form-item label="姓名:">
                <el-input v-model="empForm.name" autocomplete="off" placeholder="请输入姓名"/>
            </el-form-item>
            <el-form-item prop="password" label="工资:">
                <el-input v-model="empForm.salary" type="password" show-password placeholder="请输入工资"/>
            </el-form-item>

            <el-form-item label="性别:">
                <el-radio-group v-model="empForm.sex">
                    <el-radio value="1">男</el-radio>
                    <el-radio value="0">女</el-radio>
                </el-radio-group>
            </el-form-item>

            <el-form-item label="学历:">
                <el-select v-model="empForm.edu" placeholder="请选择学历" clearable>
                    <template v-for="option in options" :key="option.value">
                        <el-option :label="option.label" :value="option.value" />
                    </template>
                </el-select>
            </el-form-item>

            <el-form-item label="爱好:">
                <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate" @change="handleCheckAllChange">
                    全选&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                </el-checkbox>
                <el-checkbox-group v-model="empForm.hobbies" @change="handleCheckedHobbiesChange">
                    <el-checkbox v-for="hobby in hobbies" :key="hobby.value" :value="hobby.value">
                        {{ hobby.label }}
                    </el-checkbox>
                </el-checkbox-group>
            </el-form-item>

            <el-form-item label="简介:">
                <el-input v-model="empForm.description" style="width: 800px" :rows="4" type="textarea"
                    placeholder="请输入简介" />
            </el-form-item>

            <el-form-item label="日期:">
                <el-date-picker v-model="empForm.hireDate" type="date" placeholder="请选择日期" format="YYYY年MM月DD日"
                    value-format="YYYY-MM-DD" />
            </el-form-item>
        </el-form>


        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogEditFormVisible = false">取消</el-button>
                <el-button type="primary" @click="modify">
                    确认
                </el-button>
            </div>
        </template>
    </el-dialog>

</template>
<script setup>
import { ref, reactive, onMounted } from 'vue'
import { Search, DocumentAdd, CircleCheck, CircleClose, Edit, Delete } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import * as emp from '../assets/emp.js'

onMounted(() => {
    query()
})

// 查询条件
const searchForm = reactive({
    name: '',
    salary: '',
    pageSize: 2,//分页：每页显示的条数
    pageNo: 1//默认第一页
})

// 分页数据
const pageModel = reactive({
    total: 0,
    tableData: []
})


// 新增模态框，默认不显示
const dialogAddFormVisible = ref(false)

// 修改模态框，默认不显示
const dialogEditFormVisible = ref(false)

// 员工表单数据
const empForm = reactive({
    id: '',
    name: '',
    salary: '',
    sex: '',
    edu: '',
    hobbies: [],
    description: '',
    hireDate: ''
})

// 学历
const options = reactive([
    {
        value: '1',
        label: '本科'
    }, {
        value: '2',
        label: '硕士'
    }, {
        value: '3',
        label: '博士'
    }
])

// 全选
const checkAll = ref(false)

// 爱好
const hobbies = reactive([
    {
        value: '1',
        label: '吃'
    }, {
        value: '2',
        label: '玩'
    }, {
        value: '3',
        label: '睡'
    }
])

// 增加和修改模态框兴趣爱好全选
const isIndeterminate = ref(false)
function handleCheckAllChange(val) {
    empForm.hobbies = val ? ['1', '2', '3'] : [];
    isIndeterminate.value = false;
}

// 添加和修改模态框兴趣爱好全选按钮状态
function handleCheckedHobbiesChange(value) {
    const checkedCount = value.length;
    checkAll.value = checkedCount === hobbies.length;
    isIndeterminate.value = checkedCount > 0 && checkedCount < hobbies.length;
}

// 分页改变pageSize
const handleSizeChange = (size) => {
    searchForm.pageSize = size
    searchForm.pageNo = 1
    query()
}

//分页改变pageNo
const handleCurrentChange = (pageNo) => {
    searchForm.pageNo = pageNo
    query()
}

// 选中行数据
const currentRow = ref()

// 选中行
const handleCurrentRowChange = (emp) => {
  currentRow.value = emp
}

// 增删改查操作 start
import qs from 'qs'

function add() {
    console.log('add')
    console.log(qs.stringify(empForm))

    emp.add(qs.stringify(empForm))
       .then(res => {
            clear()
            query()
       })
}
function remove(row) {
    console.log('remove')
    console.log(row.id)

    ElMessageBox.confirm('此操作将永久删除该用户, 是否继续?',
                         '提示',
                         {
                            confirmButtonText: '确定',
                            cancelButtonText: '取消',
                            type: 'warning',
                         })
                .then(()=>{
                    emp.remove(row.id)
                       .then(res => {
                            query()
                            ElMessage({
                                type: 'success',
                                message: '删除成功',
                                duration:500
                            })
                       })
                       .catch(() => {
                            ElMessage({
                                type: 'info',
                                message: '已取消删除',
                                duration: 500
                            })
                       })
                })
    
}
function modifyStatus(status) {
    console.log('modifyStatus')

    console.log(status)
    console.log(currentRow.value)

    if (!currentRow.value){
        ElMessage({
            message: '请选中一行',
            type: 'warning',
        })
        return
    }

    emp.modifyStatus(currentRow.value.id,status)
       .then(res => {
            currentRow.value.status = status
            ElMessage({
                message: '恭喜你，修改成功',
                type: 'success',
                duration: 500
            })
        })
    
}
function showModify(row) {
    console.log('showModify')
    console.log(row)

    if (!row.hobbies) {
        row.hobbies = [];
    }

    // // empForm.name=row.name
    Object.assign(empForm, row)
    handleCheckedHobbiesChange(row.hobbies)

    dialogEditFormVisible.value = true
}
function modify() {
    console.log('modify')
    console.log(qs.stringify(empForm))

    emp.modify(qs.stringify(empForm))
       .then(res => {
            clear()
            query()
       })
    
}
function find() {
    console.log('find')
    searchForm.pageNo = 1
    query()
}

// 增删改查操作 end

// 条件查询
function query() {
    emp.find(searchForm)
        .then(res => {
            pageModel.total = res.data.total
            console.log(res.data.emps)
            pageModel.tableData = res.data.emps
        })
}

// 清除数据
function clear() {
    dialogAddFormVisible.value = false;
    dialogEditFormVisible.value = false;
    isIndeterminate.value = false;
    checkAll.value = false;
    Object.assign(empForm, {
        id: '',
        name: '',
        salary: '',
        sex: '',
        edu: '',
        hobbies: [],
        description: '',
        hireDate: ''
    })
}

// 表格性别格式化
function sexFormatter(row, column, cellValue) {
    const sexMap = {
        '1': '男',
        '0': '女',
    };
    return sexMap[cellValue] || ''
}

// 表格日期格式化
function dateFormatter(row, column, cellValue) {
    console.log(row.name)
    console.log(column)
    console.log(cellValue)
    if (cellValue) {
        let arr = cellValue.split('-');
        return arr[0] + '年' + arr[1] + '月' + arr[2] + '日'
    }
}

// 表格状态标签类型
function getStatusTagType(status) {
    const statusMap = {
        '1': 'success',
        '0': 'danger',
    }
    return statusMap[status] || 'info'
}

</script>